<template>
  <div>
    <el-button
      type="info"
      plain
      icon="Upload"
      v-if="type != '2'"
      @click="handleImport"
      >{{ importBtnName }}</el-button
    >
    <el-button
      type="warning"
      plain
      icon="Download"
      v-if="type != '1'"
      @click="exportData"
      >{{ exportBtnName }}</el-button
    >
    <!-- 用户导入对话框 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :auto-upload="false"
        :on-change="uploadChange"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="handleExport([])"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import * as XLSX from "xlsx";
const props = defineProps({
  type: {
    type: String,
    default: "0",
  },
  importBtnName: {
    type: String,
    default: "导入",
  },
  exportBtnName: {
    type: String,
    default: "导出",
  },
  title: {
    type: String,
    default: "导入",
  },
  keymap: {
    type: Object,
    default: {},
  },
  submitImportData: {
    type: Function,
  },
  getExportData: {
    type: Function,
  },
});
let open = ref(false);
let excelData = ref([]);
/** 导入按钮操作 */
function handleImport() {
  open.value = true;
}
//elcel预览
const uploadChange = async (e) => {
  const files = e.raw;
  if (files.length <= 0) {
    return false;
  } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
    console.log("上传格式不正确，请上传xls或者xlsx格式");
    return false;
  }
  // 读取表格
  const fileReader = new FileReader();
  fileReader.onload = (ev) => {
    const workbook = XLSX.read(ev.target.result, {
      type: "binary",
    });
    const wsname = workbook.SheetNames[0];
    const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
    // console.log(ws); // 转换成json的数据
    const m = dealExcel(ws); // ...对数据进行自己需要的操作
    excelData.value = m;
  };
  fileReader.readAsBinaryString(files);
};
//excle解析
const dealExcel = (ws) => {
  ws.forEach((sourceObj) => {
    let arr = new Array();
    Object.keys(sourceObj).map((keys) => {
      if (props.keymap[keys]) {
        sourceObj[props.keymap[keys]] = sourceObj[keys];
        delete sourceObj[keys];
      }
    });
    sourceObj["steps"] = arr;
  });
  return ws;
};
const submitFileForm = () => {
  props.submitImportData(excelData.value)
};
const exportData = () => {
  props.getExportData();
};
const handleExport = (exportData) => {
  let columns = new Array();
  let filterVal = [];
  Object.keys(props.keymap).map((keys) => {
    columns.push(keys);
    filterVal.push(props.keymap[keys]);
  });
  const exportDataNew = formatJson(filterVal, exportData);
  // 将JS数据数组转换为工作表。
  const headerWs = XLSX.utils.aoa_to_sheet([columns]);
  const ws = XLSX.utils.sheet_add_json(headerWs, exportDataNew, {
    skipHeader: true,
    origin: "A2",
  });

  /* 新建空的工作表 */
  const wb = XLSX.utils.book_new();

  // 可以自定义下载之后的sheetname
  XLSX.utils.book_append_sheet(wb, ws, "sheetName");

  /* 生成xlsx文件 */
  XLSX.writeFile(wb, "下载.xlsx");
};
// 格式化json数据
const formatJson = (filterVal, jsonData) => {
  return jsonData.map((v) =>
    filterVal.map((j) => {
      return v[j];
    })
  );
};

defineExpose({
  handleExport,
});
</script>

<style lang="scss" scoped></style>
